﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Engine.Sgml.Parser {
    internal sealed class PInstructionReader : IElementReader {

        public SElement Read(SgmlStreamReader reader, SElement parent, Context context) {
            SElement pi = parent.Nodes.Push();
            pi.Clear();
            pi.Parent = parent;
            pi.LineNumber = context.LineNumber;
            pi.LinePosition = context.LinePosition;
            pi.Name = context.NameReader.ScanNameToken(reader);
            pi.NodeType = SgmlNodeType.ProcessingInstruction;
            pi.Value = reader.ReadToEnd(new[] { Characters.ProcessingInstructionMark, Characters.EndTagMarkup, Characters.StartTagMarkup });
            if (reader.EndOfStream)
                context.TraceSource.TraceEvent(TraceEventType.Error, 0, "PI starting on {0} was not closed.", pi.Context());
            if (reader.CurrentChar == Characters.ProcessingInstructionMark)
                reader.ReadChar();
            if (reader.CurrentChar == Characters.EndTagMarkup)
                reader.ReadChar();
            return pi;
            }
        }
    }
